package cn.edu.zafu.bigdata.rwx.web;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;

public class UDPClockServer {
    private DatagramSocket socket;
    private byte[] buf;

    public UDPClockServer(int port) throws Exception {
        socket = new DatagramSocket(port);
        buf = new byte[256];
    }

    public void startServer() {
        try {
            while (true) {
                // 接收客户端请求
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                socket.receive(packet);

                // 获取服务器当前时间
                String serverTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                buf = serverTime.getBytes();

                // 发送服务器时间给客户端
                InetAddress address = packet.getAddress();
                int port = packet.getPort();
                packet = new DatagramPacket(buf, buf.length, address, port);
                socket.send(packet);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            socket.close();
        }
    }

    public static void main(String[] args) {
        int port = 12345; // 设置服务器端口
        try {
            UDPClockServer server = new UDPClockServer(port);
            server.startServer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
